<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8"><div class="grid-content bg-purple">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="userInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scoped">
            <el-switch v-model="scoped.row.mg_state" @change="stateChange(scoped.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scoped">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scoped.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scoped.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="openRolesDialog(scoped.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-size="userInfo.pagesize"
        :page-sizes="[1, 2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
     <!-- 添加用户弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="30%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改弹窗 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosde">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" >
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色分配按钮 -->
    <el-dialog
      title="角色分配"
      :visible.sync="rolesDialogVisible"
      width="30%"
      @close="rolesDialogClose">
      <div>
        <p>当前的用户 : {{ this.userObj.username }}</p>
        <p>当前的角色 : {{ this.userObj.role_name }}</p>
        <p>分配新角色 :
          <el-select v-model="value" clearable placeholder="请选择">
            <el-option
              v-for="item in rolesArr"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机号规则
    var checkPhone = (rule, value, callback) => {
      const regPhone = /^(1[3|5-9])\d{9}$/
      if (regPhone.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      userList: [],
      rolesArr: [],
      userInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 需要被分配角色的用户信息
      userObj: {},
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      rolesDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        id: 0
      },
      addFormRules: {
        username: [
          {
            required: true, message: '请输入用户名', trigger: 'blur'
          },
          {
            min: 3, max: 10, message: '用户名长度在3到10之间', trigger: 'blur'
          }
        ],
        password: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            min: 6, max: 15, message: '密码长度在6到15之间', trigger: 'blur'
          }
        ],
        email: [
          {
            required: true, message: '请输入邮箱', trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请输入电话', trigger: 'blur'
          },
          {
            validator: checkPhone, trigger: 'blur'
          }
        ]
      },
      editFormRules: {
        email: [
          {
            required: true, message: '请输入邮箱', trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请输入电话', trigger: 'blur'
          },
          {
            validator: checkPhone, trigger: 'blur'
          }
        ]
      },
      value: ''
    }
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.userInfo })
      if (res.meta.status === 200) this.userList = res.data.users
      this.total = res.data.total
    },
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('加载角色列表数据失败!')
      this.rolesArr = res.data
    },
    handleSizeChange (newSize) {
      this.userInfo.pagesize = newSize
      // 再调用接口
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.userInfo.pagenum = newPage
      this.getUserList()
    },
    async stateChange (row) {
      // 调用接口修改用户状态
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        this.$message.error('修改用户状态失败!')
        this.row.mg_status = !this.row.mg_status
      } else {
        this.$message.success('修改用户状态成功!')
      }
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    async addUser () {
      this.$refs.addFormRef.validate(async valid => {
        // 添加用户
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('新增用户失败!'); return
        }
        this.$message.success('新增用户成功!')
        // 刷新列表
        await this.getUserList()
        this.addDialogVisible = false
      })
    },
    async showEditDialog (id) {
      // 通过id查询用户信息
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        this.$message.error('获取用户信息失败!')
      } else {
        this.editForm = res.data
        // 打开弹窗
        this.editDialogVisible = true
      }
    },
    editDialogClosde () {
      this.$refs.editFormRef.resetFields()
    },
    updateUser () {
      // 调用接口修改用户信息
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + Number(this.editForm.id),
          { email: this.editForm.email, mobile: this.editForm.mobile })
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('修改用户失败!')
        } else {
          this.editDialogVisible = false
          this.$message.success('修改用户成功!')
          // 更新列表
          await this.getUserList()
        }
      })
    },
    deleteUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新列表
          await this.getUserList()
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 角色分配关闭
    rolesDialogClose () {
      this.value = ''
    },
    // 打开角色分配弹窗
    openRolesDialog (row) {
      // 加载角色列表
      this.getRolesList()
      this.userObj = row
      this.rolesDialogVisible = true
    },
    // 变更用户角色
    async updateUserRole () {
      const { data: res } = await this.$http.put(
        `users/${this.userObj.id}/role`, { rid: this.value })
      if (res.meta.status !== 200) return this.$message.error('分配用户角色失败!')
      this.$message.success('分配用户角色成功!')
      this.rolesDialogVisible = false
      await this.getUserList()
    }
  },
  created () {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>

</style>
